import json
import threading
import time

from utils.myredis import myredis
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Cate, HomePage, BrowsingHistory
from .ser import HomePageSer, CateSer, BrowsingHistorySer
from user.models import User
from user.ser import UserSer


# Create your views here.


class CateView(APIView):
    def get(self, request):
        cate = Cate.objects.all()
        cser = CateSer(cate, many=True)
        return Response(cser.data)


class HomePageView(APIView):
    def get(self, request):
        homepage = HomePage.objects.all()
        homeser = HomePageSer(homepage, many=True)
        return Response(homeser.data)


class HistoryView(APIView):
    def get(self, request):
        user = request.query_params.get('userid')
        history = BrowsingHistory.objects.filter(user_id=user)
        ser = BrowsingHistorySer(history, many=True)
        return Response({"data": ser.data})


# 缓存优化
class FindHomePage(APIView):
    def get(self, request):
        # 查询数据在redis中是否存在
        home = myredis.get_str("home")
        if home:
            # 如果存在直接返回
            return Response({"home": home})
        else:
            # 如果不存在读取数据库，存入缓存。
            # 在myredis中封装setnx分步式锁方法
            if myredis.setnx_str('home', 111):
                doc = HomePage.objects.all()
                myredis.set_str(key="home", value=json.dumps(doc))
            else:
                time.sleep(2)
                doc = myredis.get_str("home")
                return Response({"home": doc})


# class FindHomePage(APIView):
#     def get(self, request):
#         home = myredis.get_str("home")
#         if home:
#             home = json.loads(home)
#         else:
#             lock = threading.Lock()
#             with lock:
#                 # recommend=1首页推荐
#                 doc = HomePage.objects.all()
#                 # 序列化器处理
#                 home = HomePageSer(doc, many=True)
#                 myredis.set_str(key= "home",value= json.dumps(home.data))
#             # sleep(1)
#             home = myredis.get_str("home")
#             print(home)
#             if home:
#                 home = json.loads(home)
#         return Response({"home": home})


# 推荐商品
# class Comment(APIView):
#     def get(self, request):
#         # 根据用户id查到浏览记录 homepage_id
#         userid = request.query_params.get('userid')
#         history = BrowsingHistory.objects.filter(user_id=userid).values("homepage_id")
#         print(history)
#         # 拿到“我“浏览过的
#         mygoodsid = [i["homepage_id"] for i in history]
#
#         # 查询这些被哪些人浏览过
#         other = BrowsingHistory.objects.filter(homepage_id=mygoodsid).values("userid")
#         print(other)
#         theyid = [i["userid"] for i in other if i["userid"] != int(userid)]
#         print(theyid)
#         # 根据其他人的用户id获取对应的商品id
#         theygoods = BrowsingHistory.objects.filter(userid__in=theyid).values("homepage_id")
#         print(theygoods, f"他们购买的商品id")
#         theygoods = [i["homepage_id"] for i in theygoods]  # 存放至列表
#         chaji = set(theygoods).difference(mygoodsid)
#         print(chaji, f"差集")  # {3, 5}
#         # ---------------------------------------
#         # 他们的购买的商品id  1 2 3 5
#         # 我购买的商品id 1 2
#         # 差集  3 5
#         # ---------------------------------------
#         # 根据差集id拿到商品
#         comment = HomePage.objects.filter(id__in=chaji)
#         print(comment, f"推荐的商品")
#         ser = HomePageSer(comment, many=True).data
#         return Response({"comment": ser})


# 推荐
class Comment(APIView):
    def get(self, request):
        # 根据用户id查到浏览记录 homepage_id
        user_id = request.query_params.get('userid')
        history = BrowsingHistory.objects.filter(user_id=user_id).values("homepage_id")
        # print(history)
        # 拿到“我“浏览过的
        mygoodsid = [i["homepage_id"] for i in history]
        # print(mygoodsid)

        # 查询这些视频被哪些人浏览过
        other = BrowsingHistory.objects.filter(homepage_id__in=mygoodsid).values("user_id")
        # print(other)
        theyid = [i["user_id"] for i in other if i["user_id"] != int(user_id)]
        # print(theyid)
        # 根据其他人的用户id获取对应的视频id
        theygoods = BrowsingHistory.objects.filter(user_id__in=theyid).values("homepage_id")
        # print(theygoods, f"他们浏览的视频id")
        theygoods = [i["homepage_id"] for i in theygoods]  # 存放至列表
        chaji = set(theygoods).difference(set(mygoodsid))
        # print(chaji, f"差集")

        # 确保 chaji 中的元素为整数类型
        chaji = [int(item) for item in chaji]

        # 根据差集id拿到视频
        comment = HomePage.objects.filter(id__in=chaji)
        # print(comment, f"推荐的视频")
        ser = HomePageSer(comment, many=True).data
        return Response({"comment": ser})
